<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Zhishidi_Bestsellers_Block_Sidebar extends Mage_Catalog_Block_Product_Abstract {
    const  SIDEBAR_CACHE_KEY = 'zhishidi_bestsellers_sidebar';
    const  XML_BEST_SELLERS_MODEL_PATH = 'zhishidi_bestsellers/settings';
    protected $XML_ZHISHIDI_BESTSELLERS_CONFIG_PATH = 'zhishidi_bestsellers_info/sidebar/';
    protected function _construct() {
		parent::_construct();
		$this->addData(array(
			'cache_lifetime' => 86400,
			'cache_tags' => array(self::SIDEBAR_CACHE_KEY),
		));

	}
    protected function _beforeToHtml() {
        if ( $this->getModel()->isEnabled()) {
		
                $dataLimit=$this->getModel()->getLimitDate($this->getModel()->getSidebarDaysLimit());
		$collection = Mage::getResourceModel('reports/product_sold_collection')
                                //->addOrderedQty()
                                //->setStoreId($storeId)
                                ->addStoreFilter()
				->setDateRange($dataLimit['startdate'], $dataLimit['todaydate']) //
                                //->addUrlRewrite()
				->addAttributeToFilter('visibility', array('in' => array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG, Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)))
				->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED)                              
                                ->setPageSize($this->getModel()->getSidebarLimit())
                                ->setCurPage(1);


                $catId=$this->getModel()->getSidebarCategoriesID();
                if ($catId) {
                    foreach($catId as $id) {
                        $category = $this->getModel()->getCategory($id);
                        $collection->addCategoryFilter($category);
                    }
                }


		$this->setProductCollection($collection);
	}
        return parent::_beforeToHtml();
    }
    public function getModel() {
        return Mage::getModel(self::XML_BEST_SELLERS_MODEL_PATH);
    }

}

?>
